<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\model\Order;
use support\Request;
use support\Response;
use plugin\admin\app\model\Reservation;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 预约 
 */
class ReservationController extends Crud
{
    
    /**
     * @var Reservation
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new Reservation;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('reservation/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('reservation/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('reservation/update');
    }

    public function confirm(Request $request)
    {
        return view('reservation/confirm');
    }

    public function doConfirm(Request $request)
    {
        $data = $request->post();

        $reservation = Reservation::where('id', $data['id'])->first();

        Order::where('order_no', $reservation['order_no'])->update(['status' => Order::STATUS_WAITING_FINISH]);

        Reservation::where('id', $data['id'])->update(['remark' => $data['remark'], 'integral' => $data['integral'], 'finish_time' => date('Y-m-d H:i:s'), 'status' => 1]);

        return $this->json(0, '成功');
    }

    public function setStatus(Request $request)
    {
        $status = $request->post('status');

        if ($status == 1) { //已取货
            $reservation = Reservation::where('id', $request->post("id"))->first();

            $reservation->receive_time = date('Y-m-d H:i:s');
            $reservation->save();
            Order::where('order_no', $reservation['order_no'])->update(['status' => Order::STATUS_WAITING_RECEIVE, 'shipping_time' => date('Y-m-d H:i:s')]);
        } else if ($status == 2) {  //已质检
            $reservation = Reservation::where('id', $request->post("id"))->first();

            $reservation->status = 1;
            $reservation->finish_time = date('Y-m-d H:i:s');
            $reservation->save();
        }

        return $this->json('0', '成功');
    }

}
